$(document).ready(function () {
    $("#popupLogin").popup();
    $("#usedGameForm").popup();
    getAllConsoles();
    getAllGenres();
    $('#results').on('click', '.game', loadGame);
    $('#game-search-form').submit(getGames);
    $('#RegisterForm').submit(Register);
    $(document).on('click', '.rank div.star-on', function () {
        $(this).nextAll().each(function () {
            $(this).addClass('star-off').removeClass('star-on');
        });
        var number = $('.star-on').length;
        var gameId = $('#single-game').data('gameid');
        addRank(number, gameId);
    });
    $(document).on('click', '.rank div.star-off', function () {
        $(this).removeClass('star-off').addClass('star-on');
        $(this).prevAll().each(function () {
            $(this).removeClass('star-off').addClass('star-on');
        });
        $(this).nextAll().each(function () {
            $(this).addClass('star-off').removeClass('star-on');
        });
        var number = $('.star-on').length;
        var gameId = $('#single-game').data('gameid');
        addRank(number, gameId);
    });
    $(document).on('click', '.addToCart', function () {
        var parent = $(this).parent().parent();
        addItem($(parent).data('gameid'), $(parent).find('.gameTitle').html(), $(parent).find('.gamePrice').html().split('$').reverse()[0]);
        openShoppingCartWidget();
    });
    $(document).on('click', '.removeItem', removeItem);
    $(document).on('click', '#usedGameList div h3', function () {
        $(this).parent().find('p').slideToggle().parent().toggleClass('open');
    });
    $('#shoppingCartWidget span.closeWidget').click(closeShoppingCartWidget);
    $('#shoppingCartWidget span.watchShoppingCart').click(function () {
        $.mobile.changePage('#cart', 'pop', true, true);
    });
    $(document).on('click', '.watchRecommendatios', getRecommendation);

    $('#Register form').find('input[type="text"],input[type="password"],input[type="email"],input[type="number"]').blur(function () {
        if ($(this).val() != "" && $(this).parent().hasClass('errorField')) {
            $(this).parent().removeClass('errorField');
        }
    });

    $(document).on('click', '.saveCart', function () {
        $.mobile.changePage('#Payment', 'pop', true, true);
    });

    $('#Payment form').submit(saveCart);

    $(document).on('click', '.addRecommendatios', openAddRecommendation);

    $('#addRecommendation form').submit(addRecommendation);
});


function Login() {
    var target = $(this).parent().find('code');
    $.ajax({
        url: 'Login',
        dataType: 'json',
        method: 'post',
        data: $(this).serialize(),
        success: function (data) {
            $(target).html(JSON.stringify(data));
        }
    });
    return false;
}

function Register() {
    var isValid = true;
    //validation
    $(this).find('input[type="text"],input[type="password"],input[type="email"],input[type="number"]').each(function () {
        if ($(this).val() == "") {
            $(this).parent().addClass('errorField');
            isValid = false;
        } else {
            $(this).parent().removeClass('errorField');
        }
    });

    if (isValid == true) {
        $.ajax({
            url: 'Register',
            dataType: 'json',
            method: 'post',
            data: $(this).serialize(),
            success: function (data) {
                console.log(data);
                if (data.registerStatus == true) {
                    $('#registerMessage').addClass('ok');
                }
                $('#registerMessage').html(data.message);
            }
        });
    }
    return false;
}

function Logout() {
    alert('not implemented');
}

function getAllGenres() {
    $.ajax({
        url: 'AllGenres',
        dataType: 'json',
        method: 'post',
        data: {},
        success: function (data) {
            $('#allGenres').empty();
            $('#allGenres').append($('<option value="0">All</option>'));
            $(data.genres).each(function (i) {
                $('#allGenres').append($('<option value="' + data.genres[i].id + '">' + data.genres[i].name + '</option>'));
            });
        }
    });
    return false;
}

function getAllConsoles() {
    $.ajax({
        url: 'AllConsoles',
        dataType: 'json',
        method: 'post',
        data: {},
        success: function (data) {
            $('#allConsoles').empty();
            $('#allConsoles').append($('<option value="0">All</option>'));
            $(data.consoles).each(function (i) {
                $('#allConsoles').append($('<option value="' + data.consoles[i].id + '">' + data.consoles[i].name + '</option>'));
            });
        }
    });
    return false;
}

function addGenre() {
    var target = $(this).parent().find('code');
    $.ajax({
        url: 'AddGenre',
        dataType: 'json',
        method: 'post',
        data: $(this).serialize(),
        success: function (data) {
            $(target).html(JSON.stringify(data));
        }
    });
    return false;
}

function addRank(number, gameId) {
    $.ajax({
        url: 'AddRank',
        dataType: 'json',
        method: 'post',
        data: {
            gameId: gameId,
            rank: number,
            userId: 1
        },
        success: function (data) {
            console.log(data);
            getRanksForGame(gameId);
        }
    });
}

function getRanksForGame(gameId) {
    $.ajax({
        url: 'GetRanksForGame',
        dataType: 'json',
        method: 'post',
        data: {
            gameId: gameId
        },
        success: function (data) {
            $('#single-game .averageRank').html('Average Rank: ' + data.average);
        }
    });
}

function addRecommendation() {
    var form = $(this);
    $.ajax({
        url: 'AddRecommendation',
        dataType: 'json',
        method: 'post',
        data: $(this).serialize(),
        success: function (data) {
            if (data.result == true) {
                $(form).find('.addRecommendationResult').html('Your Recommendation Was Accepted!').addClass('ok');
            } else {
                $(form).find('.addRecommendationResult').html(data.message).removeClass('ok');
            }
        }
    });
    return false;
}

function getRecommendation() {
    var gameId = $('#single-game').data('gameid');
    $.ajax({
        url: 'GetRecommendation',
        dataType: 'json',
        method: 'post',
        data: {
            gameId: gameId
        },
        success: function (data) {
            //parse data
            $('#recommendationsList').empty();
            $(data.recommendations).each(function (i) {
                $('#recommendationsList').append('<li><h4 class="writtenBy"><span></span>' + data.recommendations[i].userFirstName + ' ' + data.recommendations[i].userLastName + '</h4><p>' + data.recommendations[i].recommendation + '</p></li>');
            });
            $.mobile.changePage('#recommendationsPopup', 'pop', true, true);
        }
    });
    return false;
}

function getGames() {
    $.ajax({
        url: 'GetGames',
        dataType: 'json',
        method: 'post',
        data: $(this).serialize(),
        success: parseGames
    });
    return false;
}

function addGame() {
    var target = $(this).parent().find('code');
    var formData = new FormData($(this)[0]);
    console.log(formData);
    $.ajax({
        url: 'AddGame',
        dataType: 'json',
        method: 'post',
        data: formData,
        success: function (data) {
            $(target).html(JSON.stringify(data));
        },
        cache: false,
        contentType: false,
        processData: false
    });
    return false;
}

function updateGame() {
    var target = $(this).parent().find('code');
    $.ajax({
        url: 'UpdateGame',
        dataType: 'json',
        method: 'post',
        data: $(this).serialize(),
        success: function (data) {
            $(target).html(JSON.stringify(data));
        }
    });
    return false;
}

function removeGame() {
    var target = $(this).parent().find('code');
    $.ajax({
        url: 'RemoveGame',
        dataType: 'json',
        method: 'post',
        data: {
            id: 1
        },
        success: function (data) {
            $(target).html(JSON.stringify(data));
        }
    });
    return false;
}

function addUsedGame() {
    var target = $(this).parent().find('code');
    $.ajax({
        url: 'AddUsedGame',
        dataType: 'json',
        method: 'post',
        data: $(this).serialize(),
        success: function (data) {
            $(target).html(JSON.stringify(data));
        }
    });
    return false;
}

function removeUsedGame() {
    var target = $(this).parent().find('code');
    $.ajax({
        url: 'RemoveUsedGame',
        dataType: 'json',
        method: 'post',
        data: {
            gameId: 1
        },
        success: function (data) {
            $(target).html(JSON.stringify(data));
        }
    });
    return false;
}

function getUsedGames() {
    $.ajax({
        url: 'GetUsedGames',
        dataType: 'json',
        method: 'post',
        data: {},
        success: function (data) {
            $('#usedGameList').empty();
            $(data.games).each(function (i) {
                var game = data.games[i];
                $('#usedGameList').append($('<div class="usedGame"><h3>' + game.name + '<span></span></h3><p>' + game.description + '</p>'));
            });
            $.mobile.changePage('#UsedGames', 'pop', false, true);
        }
    });
    return false;
}

function addItem(gameId, title, price) {

    $.ajax({
        url: 'AddItem',
        dataType: 'json',
        method: 'post',
        data: {
            gameId: gameId
        },
        success: function (data) {
            console.log(data);
            $('#cart ul').append($('<li class="cartItem"><span class="itemName">' + title + '</span><span class="removeItem" data-gameid="' + gameId + '"></span><span class="seperator">|</span><span class="priceTag">$' + price + '</span><div class="clearfix"></div></li>'));
            updateWidgetText();
        }
    });
    return false;
}

function removeItem() {
    var gameId = $(this).data('gameid');
    var obj = $(this);
    $.ajax({
        url: 'RemoveItem',
        dataType: 'json',
        method: 'post',
        data: {
            gameId: gameId
        },
        success: function (data) {
            $(obj).parent().remove();
            $("#cart ul").listview('refresh');
            if ($("#cart ul li.cartItem").length == 0) {
                $('#cart').dialog('close');
            }
            updateWidgetText();
        }
    });
}

function getImages() {
    var target = $(this).parent().find('code');
    $.ajax({
        url: 'GetGameImages',
        dataType: 'json',
        method: 'post',
        data: $(this).serialize(),
        success: function (data) {
            $(target).html(JSON.stringify(data));
        }
    });
    return false;
}

function saveCart() {
    $.ajax({
        url: 'SaveCart',
        dataType: 'json',
        method: 'post',
        data: $(this).serialize(),
        success: function (data) {
            if (data.result == true) {
                $('#Payment .paymentResult').html('Your Payment Was Accepted. We Will Send You The Games').addClass('ok');
            }
        }
    });
    return false;
}

function loadGame() {
    var gameId = parseInt($(this).data('gameid'));
    $.ajax({
        url: 'GetGames',
        type: 'post',
        dataType: 'json',
        data: {
            gameId: gameId
        },
        success: function (data) {
            console.log(data);
            var game = data.games;
            var largeImage = $('<img class="single-main-image" src="' + game.images[0] + '" />');
            var headline = $('<h2 class="gameTitle">' + game.name + '</h2>');
            var desc = $('<h2>Game Description</h2><p>' + game.description + '</p>');
            var thumbs = $('<h2>Screen Shots</h2>');
            var thumbsList = $('<ul class="thumbnails"></ul');
            $(game.images).each(function (i) {
                var li = $('<li><a href="' + game.images[i] + '" class="swipebox"><img src="' + game.images[i] + '" /></a></li>');
                $(thumbsList).append(li);
            });
            var youtubeId = getYoutubeId(game.trailer);
            var trailer = $('<h2>Watch Trailer</h2><div class="trailer"><a class="swipebox-video" rel="youtube" href="http://www.youtube.com/watch?v=' + youtubeId + '&autoplay=1"><img src="http://img.youtube.com/vi/' + youtubeId + '/1.jpg" /></a></div>');
            var price = $('<h2 class="gamePrice">Price: $' + game.price + '</h2>');
            var actions = $('<div class="actions"> 				<span class="watchRecommendatiosLabel">Watch Recommendations</span><div class="watchRecommendatios"></div><span class="addRecommendatiosLabel">Add Recommendations</span><div class="addRecommendatios"></div><span class="rankThisGame">Rank This Game: </span> 				<div class="rank"> 					<div class="star-off"></div> 					<div class="star-off"></div> 					<div class="star-off"></div> 					<div class="star-off"></div> 					<div class="star-off"></div> 				</div> 				<span class="averageRank">Average Rank: ' + game.rank + '</span> 				<span class="addToCartLabel">Add To Cart: </span><div class="addToCart"></div> 			</div>');

            $('#single-game').data('gameid', game.id).empty()
                .append(headline)
                .append(largeImage)
                .append(desc)
                .append(thumbs)
                .append(thumbsList)
                .append(trailer)
                .append(price)
                .append(actions);

            //refresh galleries
            $(".swipebox").swipebox();
            $(".swipebox-video").swipebox();

            jQuery.mobile.changePage('#Game');
        }
    });

}

function parseGames(data) {
    $('#results').empty();
    $(data.games).each(function (i) {
        var game = data.games[i];
        var html = '<div class="game" data-gameId="' + game.id + '"><div class="game-details"><div class="game-image"><img src="' + game.images[0] + '"></div><div class="game-name"><h2>' + game.name + '</h2><p>For ' + game.consoleName + '</p></div></div><!--<a href="" class="game-link ui-link"></a>--></div>';
        $('#results').append(html);
    });
}

function getYoutubeId(url) {
    var arr = url.split('?v=');
    return arr[arr.length - 1];
}

function showLoginForm() {
    $('#popupLogin').popup('open');
}

function showUsedGameForm() {
    $('#usedGameForm').popup('open');
}


function openShoppingCartWidget() {
    $('#shoppingCartWidget').show();
}

function closeShoppingCartWidget() {
    $('#shoppingCartWidget').hide();
}

function updateWidgetText() {
    var items = $('#cart li.cartItem').length;
    $('#shoppingCartWidget .widgetText').html('Shopping Cart: ' + items + ' items');
}

function openAddRecommendation() {
    var gameId = $(this).parent().parent().data('gameid');
    $('#recGameId').val(gameId);
    $('#addRecommendation .addRecommendationResult').empty().removeClass('ok');
    $('#addRecommendation textarea').val('');
    $.mobile.changePage('#addRecommendation', 'pop', true, true);
}